<template>
  <view class="container">
    <uni-forms ref="form" :modelValue="formData" :rules="rules">
      <uni-forms-item label="歌单" name="playlist">
        <uni-easyinput v-model="formData.playlist" placeholder="输入歌单名称" />
      </uni-forms-item>
      <uni-forms-item label="歌曲标题" name="title">
        <uni-easyinput v-model="formData.title" placeholder="输入歌曲标题" />
      </uni-forms-item>
      <uni-forms-item label="歌手" name="artist">
        <uni-easyinput v-model="formData.artist" placeholder="输入歌手名称" />
      </uni-forms-item>
      <uni-forms-item label="时长" name="duration">
        <uni-easyinput v-model="formData.duration" placeholder="输入时长(如: 03:45)" />
      </uni-forms-item>
      <uni-forms-item label="歌词" name="lyrics">
        <textarea 
          class="lyrics-textarea" 
          v-model="formData.lyrics" 
          placeholder="输入歌词(可选)" 
          maxlength="-1"
        />
      </uni-forms-item>
	  <uni-forms-item label="类型" name="type">
	    <uni-data-select v-model="formData.type" :localdata="songTypes" @change="handleTypeChange" />
	  </uni-forms-item>
      <uni-forms-item label="URL" name="url">
        <uni-easyinput v-model="formData.url" placeholder="输入歌曲URL" />
      </uni-forms-item>
      <view class="form-actions">
        <button class="submit-btn" type="primary" @click="submitForm">保存</button>
        <button class="cancel-btn" @click="goBack">取消</button>
      </view>
    </uni-forms>
  </view>
</template>

<script>
import api from '@/store/musics_api.js';

export default {
  data() {
    return {
      formData: {
        playlist: '默认歌单',
        title: '',
        artist: '',
        duration: '00:00',
        lyrics: '',
        url: '',
        type: 'network'
      },
      songTypes: [
        { value: 'network', text: '网络歌曲' },
        { value: 'local', text: '本地歌曲' }
      ],
      rules: {
        playlist: {
          rules: [{ required: true, errorMessage: '请输入歌单名称' }]
        },
        title: {
          rules: [{ required: true, errorMessage: '请输入歌曲标题' }]
        },
        url: {
          rules: [{ required: true, errorMessage: '请输入歌曲URL' }]
        },
        type: {
          rules: [{ required: true, errorMessage: '请选择歌曲类型' }]
        }
      },
      isEdit: false,
      songId: null
    }
  },
  onLoad(options) {
    if (options.id) {
      this.isEdit = true;
      this.songId = options.id;
      this.loadSongDetail();
    }
    
    // 设置标题
    uni.setNavigationBarTitle({
      title: this.isEdit ? '编辑歌曲' : '添加歌曲'
    });
  },
  methods: {
	handleTypeChange(value) {
	  // 切换类型时清空相关字段
	  if (value === 'local') {
		this.formData.url = 'http://192.168.1.42:8000/uploads/songs/';
	  }
	},
    async loadSongDetail() {
      try {
        uni.showLoading({
          title: '加载中...'
        });
        
        const [error, res] = await api.getSongDetail(this.songId, uni.getStorageSync('user').id);
        
        if (error || !res.data) {
          throw new Error('加载歌曲详情失败');
        }
        
        if (res.data.error) {
          throw new Error(res.data.message);
        }
        
        this.formData = {
          playlist: res.data.data.playlist,
          title: res.data.data.title,
          artist: res.data.data.artist || '',
          duration: res.data.data.duration || '00:00',
          lyrics: res.data.data.lyrics || '',
          url: res.data.data.url,
          type: res.data.data.type
        };
        
      } catch (error) {
        uni.showToast({
          title: error.message || '加载失败',
          icon: 'none'
        });
        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
      } finally {
        uni.hideLoading();
      }
    },
    async submitForm() {
      try {
        // 验证表单
        await this.$refs.form.validate();
        
        uni.showLoading({
          title: '保存中...',
          mask: true
        });
        
        // 准备数据
        const songData = {
          ...this.formData,
          user_id: uni.getStorageSync('user').id
        };
        
        // 根据是编辑还是添加调用不同的API
        let apiResult;
        if (this.isEdit) {
          songData.id = this.songId;
          apiResult = await api.updateSong(songData);
        } else {
          apiResult = await api.addSong(songData);
        }
        
        const [error, res] = apiResult;
        
        if (error || !res.data) {
          throw new Error('请求失败');
        }
        
        if (res.data.error) {
          throw new Error(res.data.message);
        }
        
        uni.showToast({
          title: '保存成功',
          icon: 'success'
        });
        
        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
        
      } catch (error) {
        uni.showToast({
          title: error.message || '保存失败',
          icon: 'none'
        });
      } finally {
        uni.hideLoading();
      }
    },
    goBack() {
      uni.navigateBack();
    }
  }
}
</script>

<style>
.container {
  padding: 30rpx;
}

.form-actions {
  margin-top: 60rpx;
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.submit-btn, .cancel-btn {
  height: 80rpx;
  line-height: 80rpx;
  font-size: 32rpx;
}

.cancel-btn {
  background-color: #f8f8f8;
  color: #333;
}
.lyrics-textarea {
  width: 94%;
  height: 300rpx;
  padding: 10rpx;
  border: 1rpx solid #fff;
  border-radius: 8rpx;
  font-size: 28rpx;
  line-height: 1.2;
  background-color: #fff;
  overflow-y: auto;
}
</style>